package com.unittec.drainage.provider.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;

/**
 * @Description:
 * @Author: wuxinwei
 * @CreateDate: 2019/11/8 10:44
 */
public class ZipUtils {

    /**
     * 使用GBK编码可以避免压缩中文文件名乱码
     */
    private static final String CHINESE_CHARSET = "GBK";

    /**
     * 文件读取缓冲区大小
     */
    private static final int CACHE_SIZE = 1024;

    private ZipUtils() {
        // 私用构造主法.因为此类是工具类.
    }

    /**
     * <p>
     * 压缩文件
     * </p>
     *
     * @param sourceFolder
     *            需压缩文件 或者 文件夹 路径
     * @param zipFilePath
     *            压缩文件输出路径
     * @throws Exception
     */
    public static void zip(String sourceFolder, String zipFilePath) throws Exception {
        OutputStream out = new FileOutputStream(zipFilePath);
        BufferedOutputStream bos = new BufferedOutputStream(out);
        org.apache.tools.zip.ZipOutputStream zos = new org.apache.tools.zip.ZipOutputStream(bos);
        // 解决中文文件名乱码
        zos.setEncoding(CHINESE_CHARSET);
        File file = new File(sourceFolder);
        String basePath = null;
        if (file.isDirectory()) {
            basePath = file.getPath();
        } else {
            basePath = file.getParent();
        }
        zipFile(file, basePath, zos);
        zos.closeEntry();
        zos.close();
        bos.close();
        out.close();
    }

    /**
     * <p>
     * 压缩文件
     * </p>
     *
     * @param sourceFolders
     *            一组 压缩文件夹 或 文件
     * @param zipFilePath
     *            压缩文件输出路径
     * @throws Exception
     */
    public static void zip(String[] sourceFolders, String zipFilePath) throws Exception {
        OutputStream out = new FileOutputStream(zipFilePath);
        BufferedOutputStream bos = new BufferedOutputStream(out);
        org.apache.tools.zip.ZipOutputStream zos = new org.apache.tools.zip.ZipOutputStream(bos);
        // 解决中文文件名乱码
        zos.setEncoding(CHINESE_CHARSET);

        for (int i = 0; i < sourceFolders.length; i++) {
            File file = new File(sourceFolders[i]);
            String basePath = null;
            basePath = file.getParent();
            zipFile(file, basePath, zos);
        }

        zos.closeEntry();
        zos.close();
        bos.close();
        out.close();
        // logger.debug("压缩 " + ArrayUtil.join(sourceFolders) + " 完成！");
    }

    /**
     * <p>
     * 递归压缩文件
     * </p>
     *
     * @param parentFile
     * @param basePath
     * @param zos
     * @throws Exception
     */
    private static void zipFile(File parentFile, String basePath, org.apache.tools.zip.ZipOutputStream zos)
        throws Exception {
        File[] files = new File[0];
        if (parentFile.isDirectory()) {
            files = parentFile.listFiles();
        } else {
            files = new File[1];
            files[0] = parentFile;
        }
        String pathName;
        InputStream is;
        BufferedInputStream bis;
        byte[] cache = new byte[CACHE_SIZE];
        for (File file : files) {
            if (file.isDirectory()) {

                basePath = basePath.replace('\\', '/');
                if (("/").equals(basePath.substring(basePath.length() - 1))) {
                    pathName = file.getPath().substring(basePath.length()) + "/";
                } else {
                    pathName = file.getPath().substring(basePath.length() + 1) + "/";
                }

                zos.putNextEntry(new org.apache.tools.zip.ZipEntry(pathName));
                zipFile(file, basePath, zos);
            } else {
                pathName = file.getPath().substring(basePath.length());
                pathName = pathName.replace('\\', '/');
                if (("/").equals(pathName.substring(0, 1))) {
                    pathName = pathName.substring(1);
                }
                is = new FileInputStream(file);
                bis = new BufferedInputStream(is);
                zos.putNextEntry(new org.apache.tools.zip.ZipEntry(pathName));
                int nRead = 0;
                while ((nRead = bis.read(cache, 0, CACHE_SIZE)) != -1) {
                    zos.write(cache, 0, nRead);
                }
                bis.close();
                is.close();
            }
        }
    }

    /**
     * 解压zip文件
     *
     * @param zipFileName
     *            待解压的zip文件路径，例如：c:\\a.zip
     * @param outputDirectory
     *            解压目标文件夹,例如：c:\\a\
     */
    public static void unZip(String zipFileName, String outputDirectory) throws Exception {
        org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(zipFileName, CHINESE_CHARSET);
        try {

            Enumeration<?> e = zipFile.getEntries();

            org.apache.tools.zip.ZipEntry zipEntry = null;

            createDirectory(outputDirectory, "");

            while (e.hasMoreElements()) {

                zipEntry = (org.apache.tools.zip.ZipEntry)e.nextElement();

                if (zipEntry.isDirectory()) {

                    String name = zipEntry.getName();

                    name = name.substring(0, name.length() - 1);

                    File f = new File(outputDirectory + File.separator + name);

                    f.mkdir();

                } else {
                    File f = new File(outputDirectory + File.separator + zipEntry.getName());
                    f.createNewFile();
                    try (InputStream in = zipFile.getInputStream(zipEntry);
                        FileOutputStream out = new FileOutputStream(f)) {
                        byte[] by = new byte[1024];
                        int c;
                        while ((c = in.read(by)) != -1) {
                            out.write(by, 0, c);
                        }
                    } catch (IOException e1) {
                        System.out.println(e1.getMessage());
                    }
                }

            }

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            zipFile.close();
        }

    }

    /**
     * 创建目录
     *
     * @param directory
     * @param subDirectory
     * @author hezhao
     * @Time 2017年7月28日 下午7:10:05
     */
    private static void createDirectory(String directory, String subDirectory) {

        String[] dir;

        File fl = new File(directory);

        try {

            if (subDirectory == "" && fl.exists() != true) {

                fl.mkdir();

            } else if (subDirectory != "") {

                dir = subDirectory.replace('\\', '/').split("/");

                for (int i = 0; i < dir.length; i++) {

                    File subFile = new File(directory + File.separator + dir[i]);

                    if (subFile.exists() == false) {
                        subFile.mkdir();
                    }
                    directory += File.separator + dir[i];

                }

            }

        } catch (Exception ex) {

            System.out.println(ex.getMessage());

        }

    }

    /**
     * 无需解压直接读取Zip文件和文件内容
     *
     * @param file
     *            文件
     * @throws Exception
     * @author hezhao
     * @Time 2017年7月28日 下午3:23:10
     */
    public static void readZipFile(String file) throws Exception {
        java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(file);
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        java.util.zip.ZipInputStream zin = new java.util.zip.ZipInputStream(in);
        java.util.zip.ZipEntry ze;
        while ((ze = zin.getNextEntry()) != null) {
            if (ze.isDirectory()) {
            } else {
                long size = ze.getSize();
                if (size > 0) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(ze)));
                    String line;
                    while ((line = br.readLine()) != null) {
                        System.out.println(line);
                    }
                    br.close();
                }
                System.out.println();
            }
        }
        zin.closeEntry();
    }

    public static void main(String[] args) throws Exception {
        try {
            String sourceFolder = "C:\\Users\\wuxinwei\\Desktop\\集装箱12364.zip";
            String zipFilePath = "D:\\集装箱222333";
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
